package com.py.credit.service.impl;

import com.alibaba.fastjson.JSON;
import com.py.credit.common.Page;
import com.py.credit.common.rest.RestServiceResult;
import com.py.credit.dao.LhjcBatchFileDao;
import com.py.credit.dao.LhjcBatchLogDao;
import com.py.credit.entity.*;
import com.py.credit.entity.common.LogEnum;
import com.py.credit.service.LhjcBatchLogService;
import com.py.credit.service.LhjcWriteLogsService;
import com.py.credit.utils.DateUtil;
import com.py.credit.utils.FileUtil;
import com.py.credit.utils.NewBatchIdUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * 批次日志ServiceImpl
 *
 * @author gongsi
 */
@Service
public class LhjcBatchLogServiceImpl implements LhjcBatchLogService {

    @Autowired
    private LhjcBatchLogDao lhjcBatchLogDao;

    @Autowired
    private LhjcBatchFileDao lhjcBatchFileDao;

    @Autowired
    private LhjcWriteLogsService lhjcWriteLogsService;

    /**
     * 上传文件
     */
    private void fileUpload(MultipartFile file, String pathFile, String batchId, String fileType) {
        File uploadFile = null;

        File dirPath = new File(pathFile);
        uploadFile = new File(pathFile + File.separator + batchId + fileType);
        if (!dirPath.exists()) {
            uploadFile.mkdirs();
        }

        try {
            file.transferTo(uploadFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 更新批次日志
     */
    @Override
    public void modify(String batchId, String result, int scount, int tcount, int fcount, int rcount, String status) {
        lhjcBatchLogDao.update(batchId, result, scount, tcount, fcount, rcount, status);
    }

    @Override
    public List<LhjcBatchLog> getListForPage(String startTime, String endTime, String batchId, String realName, String target, String result, Page page) {
        return lhjcBatchLogDao.getListForPage(startTime, endTime, batchId, realName, target, result, page);
    }

    @Override
    public void modify(String batchId, String status) {
        lhjcBatchLogDao.updateStatus(batchId, status);
    }

    @Override
    public RestServiceResult doUploadFile(String absolutepath, LhjcCube cube, MultipartFile file, SysUser manager) {

        // 组织机构代码
        String orgBm = manager.getOfficeId() + "";

        String batchId = NewBatchIdUtil.getInstance().buildNewBatchId(orgBm, cube);

        // 文件存储路径
        StringBuilder pathFile = new StringBuilder(200);
        pathFile.append(File.separator);
        pathFile.append(orgBm);
        pathFile.append(File.separator);
        pathFile.append(cube.getCubeCode());

        // 获取文件的后缀
        String fileType = null;
        if (file != null) {
            // 获取文件后缀
            if (file.getOriginalFilename().contains(".")) {
                fileType = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."),
                        file.getOriginalFilename().length());
            }
        } else {
            return new RestServiceResult(RestServiceResult.CODE_UNKNOW, "上传的文件不得为空");
        }

        if (!".xls".equalsIgnoreCase(fileType) && !".xlsx".equalsIgnoreCase(fileType)) {
            return new RestServiceResult(RestServiceResult.CODE_UNKNOW, "上传的文件格式不支持。");
        }

        // 先存储文件
        fileUpload(file, absolutepath + File.separator + "upload" + pathFile.toString(), batchId.toString(),
                fileType);

        // 添加文件记录
        lhjcBatchFileDao.insert(batchId, batchId + fileType, pathFile.toString() + File.separator, "");

        // 添加批次日志
        lhjcBatchLogDao.insert(batchId, cube.getCubeId(), "0", 0, orgBm, "0", manager.getId(),
                LogEnum.WCL, manager.getRealName());

        return new RestServiceResult(batchId);
    }

    @Override
    public List<LhjcBatchFile> getUntreatedFiles() {
        return lhjcBatchFileDao.getUntreatedFiles();
    }

    @Override
    public LhjcBatchLog select(String batchId) {
        return lhjcBatchLogDao.select(batchId);
    }

    @Override
    public void updateBatchLogValStatus(String batchId, String valStatus) {
        lhjcBatchLogDao.updateStatus(batchId, valStatus);
    }

    @Override
    public void fileDownload(String absolutepath, String batchId, HttpServletResponse response) {
        LhjcBatchFile batchFile = lhjcBatchFileDao.select(batchId);
        String path = absolutepath + File.separator + "upload" + batchFile.getFpath() + batchFile.getFname();

        FileUtil.downloadFile(path, response);
    }

    @Override
    public void logDownload(String absolutepath, String batchId, HttpServletResponse response) {
        String logPath = lhjcWriteLogsService.readLogFilePath(absolutepath, batchId);
        FileUtil.downloadFile(logPath, response);
    }

    @Override
    public Map<String, Object> getDayStat(List<LhjcBatchStat> objList, String orgBm) {

        Map<String, Object> map = new HashMap<String, Object>();

        // 获取当月所有天的日期
        List<String> dayList = getMonthDayUntil();

        // 数据结果
        List<LhjcStatBean> result = new ArrayList<LhjcStatBean>();

        // 名称
        List<String> nameList = new ArrayList<String>();

        // 循环获取数据
        String objName = null;
        int objId = 0;

        List<LhjcBatchStat> dataList;
        List<Integer> countList = null;
        LhjcStatBean statBean = null;
        for (LhjcBatchStat stat : objList) {
            objName = stat.getTableNameCn();
            objId = stat.getTableId();
            countList = new ArrayList<Integer>();

            // 组装名称
            nameList.add(objName);

            // 获取数据
            dataList = lhjcBatchLogDao.getDayData(orgBm, objId);

            statBean = new LhjcStatBean();
            statBean.setName(objName);

            // 拼接每日数据
            for (String day : dayList) {
                boolean isContent = false;
                for (LhjcBatchStat batchStat : dataList) {
                    if (day.equals(batchStat.getExTime())) {
                        countList.add(batchStat.getTcount());
                        isContent = true;
                        break;
                    }
                }

                if (!isContent) {
                    countList.add(0);
                }
            }
            statBean.setData(countList);
            result.add(statBean);
        }

        map.put("dayList", JSON.toJSONString(dayList));
        map.put("nameList", JSON.toJSONString(nameList));
        map.put("result", JSON.toJSONString(result));

        return map;
    }

    /**
     * 获取到截止日期的当月所有日期
     *
     * @return
     */
    private List<String> getMonthDayUntil() {
        List<String> list = new ArrayList<String>();
        Calendar cal = Calendar.getInstance();

        int today = cal.get(Calendar.DAY_OF_MONTH);

        cal.set(Calendar.DAY_OF_MONTH, 1);
        int month = cal.get(Calendar.MONTH);
        while (cal.get(Calendar.MONTH) == month && today >= cal.get(Calendar.DAY_OF_MONTH)) {
            list.add(DateUtil.getInstance().dateToStr(cal.getTime(), DateUtil.MM_DD));
            cal.add(Calendar.DAY_OF_MONTH, 1);
        }

        return list;
    }

    @Override
    public void add(String batchId, int target, String type, int dataSourceId, String orgBm, String result,
                    long managerId, String status, String realName) {
        lhjcBatchLogDao.insert(batchId, target, type, dataSourceId, orgBm, result, managerId, status, realName);
    }

    @Override
    public void updateUpdateTimeAndUpdateStatus(String batchId, String updateStatus) {

        if (StringUtils.isBlank(batchId)) {
            //批次号不能为空
            return;
        }

        lhjcBatchLogDao.updateStatus(batchId, updateStatus);
    }

    /**
     * 模板下载
     */
    @Override
    public void downloadFilemb(String target, HttpServletResponse response) {
        String logPath = "";
        if (target.equals("1002") || target.equals("1003") || target.equals("1004")) {
            logPath = LhjcBatchLogServiceImpl.class.getClassLoader().getResource("mb/mb.rar").getPath();
        }
        FileUtil.downloadFile(logPath, response);
    }

    @Override
    public LhjcCube queryCubeById(int cubId) {
        return lhjcBatchLogDao.queryCubeById(cubId);
    }
}
